   /*
 * Project name:
   Smart Digital Clock
 * Copyright:
     (c) Hamita JSC, 2013.
 * Author :
     ToanRV
 * Revision History:
     2013_06_04( YYMMDD):
       - initial release (FJ);    2013_06_04
       - Day of begining project: 2013_05_16
 * Description:
     V1:2013_06_04  Smart Digital Clock used RTC DS1307, Set data time via LCD 
         and key broad
     V2:

 * Test configuration:
     MCU:             PIC16F877A
     dev.board:       PICLAB-V2 TMe
     Oscillator:      4.0000 MHz Crystal
     Ext. Modules:    None.
     SW:              mikroC PRO for PIC
                      http://www.mikroe.com/eng/products/view/7/mikroc-pro-for-pic/
 * NOTES:
  /*
 *******************************************************************************
                         Define preprocesser statement
*TEST_MODULE = 1: LED Blinking                 Ok
*TEST_MODULE = 2: LCD                          OK
*TEST_MODULE = 3: Keypad with LCD              OK
*TEST_MODULE = 4: Button Process               OK
*TEST_MODULE = 5: 7segment, count 0-99.Not using timer, Status: Finished
*TEST_MODULE = 5.1(51):7segment, count 0-99.Used Timer0 Status: Finished
                       Timer fomular: x(prescaler).y(TMR0)=E6.(Fosc/4).Timer_Interrupt_Time
                       To used TMRO0 in interrupt mode, T0CS must be set zero
                       7Segment flashing frequency is about 60Hz-120HZ
*TEST_MODULE = 5.2(52):7segment, count 0-99.Used Timer1(16bit) Status: 6/14/2013  Ok
                       Timer fomular: x(prescaler).y(TMR0)=E6.(Fosc/4).Timer_Interrupt_Time
                       To used TMRO0 in interrupt mode, T0CS must be set zero
                       7Segment flashing frequency is about 60Hz-120HZ
                       Transmit and receiver data via UART  Date: 6/14/2013 Status: OK
                       
*TEST_MODULE = 5.3(53):USART : External Interupt and Central remoote Control V1


*TEST_MODULE = 6: Main project: display and set sec, min, hour, day, month, year
                                via LCD.
                                RB1(UP), RB2(DOWN), RB3(SET), RB4(menu)
                                Status : Finished

*TEST_MODULE = 7: Main project, display sec, min, hour via 7segment.
                                Set sec, min, hour via 7segment and button
                                RB1(UP), RB2(DOWN), RB3(SET), RB4(menu)
                                Status: Finished

*TEST_MODULE = 8: USART
*TEST_MODULE = 9: DB18B20 -OneWire Temperature measurment
*TEST_MODULE = 10: ADC, Read Variable Resistance
*TEST_MODULE = 11: SPI, Communicate with EEPROM
*TEST_MODULE = 12: Human Machine Interface( Recommended by Mr Duong Tran Binh )
    LCD, button or KeyPad, For example: measure Temperature and send to PC via
    USART
*TEST_MODULE = 13: PWM
    
 *******************************************************************************
 */
 #define TEST_MODULE 53
 #include "DS1307.h"
//////////////DECLARE VARIABLE /////////////////////////////////////////////////
 #if ( TEST_MODULE ==1 )
 #elif( TEST_MODULE == 2)
     // LCD module connections
     sbit LCD_RS at RA1_bit;
     sbit LCD_EN at RA3_bit;
     sbit LCD_D4 at RD4_bit;
     sbit LCD_D5 at RD5_bit;
     sbit LCD_D6 at RD6_bit;
     sbit LCD_D7 at RD7_bit;

     sbit LCD_RS_Direction at TRISA1_bit;
     sbit LCD_EN_Direction at TRISA3_bit;
     sbit LCD_D4_Direction at TRISD4_bit;
     sbit LCD_D5_Direction at TRISD5_bit;
     sbit LCD_D6_Direction at TRISD6_bit;
     sbit LCD_D7_Direction at TRISD7_bit;
     // End LCD module connections
 #elif( TEST_MODULE == 3)
      // LCD module connections
     sbit LCD_RS at RA1_bit;
     sbit LCD_EN at RA3_bit;
     sbit LCD_D4 at RD4_bit;
     sbit LCD_D5 at RD5_bit;
     sbit LCD_D6 at RD6_bit;
     sbit LCD_D7 at RD7_bit;

     sbit LCD_RS_Direction at TRISA1_bit;
     sbit LCD_EN_Direction at TRISA3_bit;
     sbit LCD_D4_Direction at TRISD4_bit;
     sbit LCD_D5_Direction at TRISD5_bit;
     sbit LCD_D6_Direction at TRISD6_bit;
     sbit LCD_D7_Direction at TRISD7_bit;
     // End LCD module connections
 #elif( TEST_MODULE == 4)
 #elif( TEST_MODULE == 5)
  const char SevenSegment_DATA[10]={0xC0,0xF9,0xA4,0xB0,0x99,    // 0 1 2 3 4
                                    0x92,0x82,0xF8,0x80,0x90 };  // 5 6 7 8 9
                   // define constant 0-5 data table, 7segment common anode
 const char SevenSegment_DRIVE[6]= {0x3E, 0x3D, 0x3B, 0x37, 0x2F, 0X1F };
                                   // RA0-Q1 RA1-Q2 RA2-Q3
                                   // RA4-Q1 RA5-Q2 RA5-Q6
 #elif( TEST_MODULE == 6)
 #elif( TEST_MODULE == 7)
 #elif( TEST_MODULE == 8)
 #elif( TEST_MODULE == 9)
 #elif( TEST_MODULE == 10)
 #endif
 /////////////////END OF DECLARE VARIABLE///////////////////////////////////////
 //////////////// DECLARE INTERRUPT FUNCTION///////////////////////////////////

 #if ( TEST_MODULE ==1 )
 #elif( TEST_MODULE == 2)
 #elif( TEST_MODULE == 3)
 #elif( TEST_MODULE == 4)
 #elif( TEST_MODULE == 5)
 #elif( TEST_MODULE == 6)
 #elif( TEST_MODULE == 7)
 #elif( TEST_MODULE == 8)
 #elif( TEST_MODULE == 9)
 #elif( TEST_MODULE == 10)
 #endif

///////////////////END OF DECLARE INTERRUPT FUNCTION////////////////////////////
/////////////////// MAIN FUNCTION///////////////////////////////////////////////
 #if ( TEST_MODULE ==1 )
 void main(void) {
     PORTC      = 0;
     TRISC      = 0b00111111;
     while (1){
         PORTC = 0xff;
         Delay_ms(1000);
         PORTC = 0x00;
         Delay_ms(1000);
     }
 }
 #elif( TEST_MODULE == 2)

     char txt1[] = "mikroElektronika";
     char txt2[] = "EasyPIC6";
     char txt3[] = "Lcd4bit";
     char txt4[] = "example";
     
     char i;                              // Loop variable

 void main(void){
     TRISA1_bit = 0;
     TRISA2_bit = 0;
     TRISA3_bit = 0;
     TRISD4_bit = 0;
     TRISD5_bit = 0;
     TRISD6_bit = 0;
     TRISD7_bit = 0;
     ADCON1 = 0x06;                     //All pin of PORTA are Digital I/O

     Lcd_Init();                        // Initialize LCD

     Lcd_Cmd(_LCD_CLEAR);               // Clear display
     Lcd_Cmd(_LCD_CURSOR_OFF);          // Cursor off
     Lcd_Out(1,6,txt3);                 // Write text in first row

     Lcd_Out(2,6,txt4);                 // Write text in second row
     Delay_ms(2000);
     Lcd_Cmd(_LCD_CLEAR);               // Clear display

     Lcd_Out(1,1,txt1);                 // Write text in first row
     Lcd_Out(2,5,txt2);                 // Write text in second row

     Delay_ms(2000);

     // Moving text
     for(i=0; i<4; i++) {               // Move text to the right 4 times
         Lcd_Cmd(_LCD_SHIFT_RIGHT);
         Delay_ms(500);
     }

     while(1) {                         // Endless loop
         for(i=0; i<8; i++) {             // Move text to the left 7 times
             Lcd_Cmd(_LCD_SHIFT_LEFT);
             Delay_ms(500);
         }

         for(i=0; i<8; i++) {             // Move text to the right 7 times
             Lcd_Cmd(_LCD_SHIFT_RIGHT);
             Delay_ms(500);
         }
     }
 }

 #elif( TEST_MODULE == 3)

 unsigned char Keypad_ScanCode [4]  = { 0x07, 0x0B, 0x0D, 0x0E };
 unsigned char Keypad_ASCIICode[4][4] = { '7', '8', '9', '/',
                                          '4', '5', '6', '*',
                                          '1', '2', '3', '-',
                                          'N', '0', '=', '+' };

 unsigned char Key ;
 char txt[6];

 unsigned short Keypad_Scan();

 void main (void){
     //LCD pin declaration
     TRISA1_bit = 0;
     TRISA2_bit = 0;
     TRISA3_bit = 0;
     TRISD4_bit = 0;
     TRISD5_bit = 0;
     TRISD6_bit = 0;
     TRISD7_bit = 0;
     ADCON1 = 0x07;                           //All pin of PORTA are Digital I/O
     //Endless of LCD pin declaration
     
     // Keypad pin Declaration
     TRISC = 0b00001111;                     // 4 higher bits as output
                                             // 4 lower bits as input
     PORTC = 0xF0 ;                          // 4 higher bits are '1' logic
     // Endless of Keypad declaration
     
     Lcd_Init();                              // Initialize LCD
     Lcd_Cmd(_LCD_CLEAR);                     // Clear display
     Lcd_Cmd(_LCD_CURSOR_OFF);                // Cursor off
     //Lcd_Out(1, 1, "1");
     Lcd_Out(1, 1, "Key  :");                 // Write message text on LCD
     Lcd_Out(2, 1, "Times:");
     
     while (1){
         Key = Keypad_Scan();
         if(Key){
             //WordToStr( Key, txt);
             Lcd_chr(1 , 7 ,Key);
         }
     }
 }
  unsigned char Keypad_Scan() {
     unsigned char i, j, Keypad_in = 0;
     for(i= 0; i< 4; i++){
         PORTC = 0xFF - (1 << (i+4));
         asm{nop;}
         //Delay_us( 10);
         Keypad_in = PORTC;
         // Bat su kien co nut nhan//
         Keypad_in = Keypad_in & 0x0F ;
         
         if (Keypad_in != 0x0F)
             for(j= 0; j < 4; j++){
                 if ( Keypad_in == Keypad_ScanCode[j])
                      return Keypad_ASCIIcode[i][j];
             }
     }
         return 0;
 }
 #elif( TEST_MODULE == 4)
 void main(void){
 
     TRISC      = 0b00111111;
     PORTC      = 0xff;
     
     TRISB = 0b00001111 ;           // 4 lower  bits are set as input
     OPTION_REG = 0x00 ;             //Enable pull-up resistor in PORTB

     while (1){

         if((Button( &PORTB, 0, 1, 0))|| (Button( &PORTB, 1, 1, 0))
           ||(Button( &PORTB, 2, 1, 0))|| (Button( &PORTB, 3, 1, 0 )))
             {PORTC = 0x00; }
         else PORTC =~ PORTC ;
     }
 }
 #elif( TEST_MODULE == 5)
 
 unsigned long i = 0;
 unsigned short cnt = 0;
 
 void SevenSegmnet_Display( unsigned short n);
 void delay();
 
 void main(void){
 
     ADCON1 = 0x06;                     //All pin of PORTA are Digital I/O
     TRISA  = 0b11000000 ;
     PORTA  = 0x3F ;                   // Clear all 7segment
     
     TRISD  =0x00 ;
     PORTD  =0x00 ;                    //
     
     while(1){

         
             for( i= 0 ; i <= 50 ; i++){
                 SevenSegmnet_Display(cnt);
                 //Delay_ms(500);
             }
             cnt=(cnt==99) ? 1: cnt+1; // increse count

     }
 
 
 }
 void SevenSegmnet_Display( unsigned short n){
 
     unsigned short i = 0;
     
     i = SevenSegment_DATA[n/10];
     PORTD = i;
     PORTA = SevenSegment_DRIVE[4];
     Delay_ms(5);
     //delay();
     
     i = SevenSegment_DATA[n% 10];
     PORTA = SevenSegment_DRIVE[5];
     PORTD = i;
     Delay_ms(5);
     //delay();
 }
  void  delay()              //delay function
    {
     int i;                 //
     for(i=0x100;i--;);     //delay
    }
 #elif( TEST_MODULE ==51)
 const char SevenSegment_DATA[10]={0xC0,0xF9,0xA4,0xB0,0x99,    // 0 1 2 3 4
                                    0x92,0x82,0xF8,0x80,0x90 };  // 5 6 7 8 9
                   // define constant 0-5 data table, 7segment common anode
 const char SevenSegment_DRIVE[6]= {0x3E, 0x3D, 0x3B, 0x37, 0x2F, 0X1F };
                                   // RA0-Q1 RA1-Q2 RA2-Q3
                                   // RA4-Q1 RA5-Q2 RA5-Q6
 unsigned short cnt;
 unsigned short Cnt_Timer0;
 bit Segment_DRIVE;
 unsigned short i;
 void interrupt(void){
     if( TMR0IF_bit){           // Select Timer0 overload Interrupt
         Segment_DRIVE = ~Segment_DRIVE;
         //PORTC= ~PORTC;
         Cnt_Timer0++;
         if(Cnt_Timer0==122){
             cnt++;
             Cnt_Timer0 = 0;
             if(cnt==100){
                 cnt=0;
             }
         }
     }
     TMR0 = 0x00;
     TMR0IF_bit = 0;
 }
 void main(void){
 
     ADCON1 = 0x06;                     //All pin of PORTA are Digital I/O
     TRISA  = 0b11000000 ;
     PORTA  = 0x3F ;                   // Clear all 7segment

     TRISD  =0x00 ;
     PORTD  =0x00 ;
     
     TRISC = 0x00;
     PORTC = 0x00;
     
     //OPTION_REG = 0x00 ;        //Enable pull-up resistor in PORTB and select HS Oscillator Source clock
/*
     bit 7 RBPU: PORTB Pull-up Enable bit
         1 = PORTB pull-ups are disabled
         0 = PORTB pull-ups are enabled by individual port latch values
     bit 6 INTEDG: Interrupt Edge Select bit
         1 = Interrupt on rising edge of RB0/INT pin
         0 = Interrupt on falling edge of RB0/INT pin
     bit 5 T0CS: TMR0 Clock Source Select bit
         1 = Transition on RA4/T0CKI pin
         0 = Internal instruction cycle clock (CLKO)
     bit 4 T0SE: TMR0 Source Edge Select bit
         1 = Increment on high-to-low transition on RA4/T0CKI pin
         0 = Increment on low-to-high transition on RA4/T0CKI pin
     bit 3 PSA: Prescaler Assignment bit
         1 = Prescaler is assigned to the WDT
         0 = Prescaler is assigned to the Timer0 module
     bit 2-0 PS2:PS0: Prescaler Rate Select bits
     Bit Value     TMR0 Rate     WDT Rate
     PS2-PS0
     000           1 : 2         1 : 1
     001           1 : 4         1 : 2
     010           1 : 8         1 : 4
     011           1 : 16        1 : 8
     100           1 : 32        1 : 16
     101           1 : 64        1 : 32
     110           1 : 128       1 : 64
     111           1 : 256       1 : 128
*/
     INTCON = 0b10000000;
     OPTION_REG = 0x00;// select HS Oscillator Source clock for Timer0


     /*
     INTCON: Interrupt control Register
     GIE  PEIE  TMR0IE  INTE  RBIE  TMR0IF  INTF  RBIF
     bit7                                         bit0
     bit 7 GIE: Global Interrupt Enable bit
         1 = Enables all unmasked interrupts
         0 = Disables all interrupts
     bit 6 PEIE: Peripheral Interrupt Enable bit
         1 = Enables all unmasked peripheral interrupts
         0 = Disables all peripheral interrupts
     bit 5 TMR0IE: TMR0 Overflow Interrupt Enable bit
         1 = Enables the TMR0 interrupt
         0 = Disables the TMR0 interrupt
     bit 4 INTE: RB0/INT External Interrupt Enable bit
         1 = Enables the RB0/INT external interrupt
         0 = Disables the RB0/INT external interrupt
     bit 3 RBIE: RB Port Change Interrupt Enable bit
         1 = Enables the RB port change interrupt
         0 = Disables the RB port change interrupt
     bit 2 TMR0IF: TMR0 Overflow Interrupt Flag bit
         1 = TMR0 register has overflowed (must be cleared in software)
         0 = TMR0 register did not overflow
     bit 1 INTF: RB0/INT External Interrupt Flag bit
         1 = The RB0/INT external interrupt occurred (must be cleared in software)
         0 = The RB0/INT external interrupt did not occur
     bit 0 RBIF: RB Port Change Interrupt Flag bit
         1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to set
         the bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared
         (must be cleared in software).
         0 = None of the RB7:RB4 pins have changed state
     */
     
     PS0_bit = 0;            //Set Source clock 1:32, interrupt each 8ms
     PS1_bit = 0;
     PS2_bit = 1;
     
     cnt = 0;
     Cnt_Timer0 = 0;
     TMR0 = 0x00;
     Segment_DRIVE = 1;
     TMR0IE_bit = 1;             // Enable TMRO interrupt
     i = 0;
     
     while(1){
         switch(Segment_DRIVE){
         
             case 0:
                 i =SevenSegment_DATA[cnt%10];  //tranh hien tuong bong ma, dua cac gia tri vao bien dem i
                 PORTA = SevenSegment_DRIVE[5];
                 PORTD = i;

                 break;
             case 1:
                 i = SevenSegment_DATA[cnt/10];
                 PORTA = SevenSegment_DRIVE[4];
                 PORTD = i;
                 break;
         }
         


         
     }
 }
 #elif( TEST_MODULE ==52)
const char SevenSegment_DATA[10]={0xC0,0xF9,0xA4,0xB0,0x99,    // 0 1 2 3 4
                                    0x92,0x82,0xF8,0x80,0x90 };  // 5 6 7 8 9
                   // define constant 0-5 data table, 7segment common anode
 const char SevenSegment_DRIVE[6]= {0x3E, 0x3D, 0x3B, 0x37, 0x2F, 0X1F };
                                   // RA0-Q1 RA1-Q2 RA2-Q3
                                   // RA4-Q1 RA5-Q2 RA5-Q6
 unsigned short cnt;
 unsigned short Cnt_Timer0;
 bit Segment_DRIVE;
 unsigned short i;
 bit USART_Display;
 char txt[7];
 void interrupt(void){
     if( PIR1.TMR1IF){           // Select Timer0 overload Interrupt
         Segment_DRIVE = ~Segment_DRIVE;
         //PORTC= ~PORTC;
         Cnt_Timer0++;
         if(Cnt_Timer0==122){
             cnt++;
             USART_Display = 1;
             Cnt_Timer0 = 0;
             if(cnt==100){
                 cnt=0;
             }
         }
         TMR1H = 0xFB;
         TMR1L = 0xFF;
         PIR1.TMR1IF = 0;
     }
     if(INTF_bit){
         cnt =0;
         INTF_bit = 0;
     }

 }
 void main(void){

     ADCON1 = 0x06;                     //All pin of PORTA are Digital I/O
     TRISA  = 0b11000000 ;
     PORTA  = 0x3F ;                   // Clear all 7segment

     TRISD  =0x00 ;
     PORTD  =0x00 ;

     TRISC = 0x00;
     PORTC = 0x00;

     //OPTION_REG = 0x00 ;        //Enable pull-up resistor in PORTB and select HS Oscillator Source clock
/*
     bit 7 RBPU: PORTB Pull-up Enable bit
         1 = PORTB pull-ups are disabled
         0 = PORTB pull-ups are enabled by individual port latch values
     bit 6 INTEDG: Interrupt Edge Select bit
         1 = Interrupt on rising edge of RB0/INT pin
         0 = Interrupt on falling edge of RB0/INT pin
     bit 5 T0CS: TMR0 Clock Source Select bit
         1 = Transition on RA4/T0CKI pin
         0 = Internal instruction cycle clock (CLKO)
     bit 4 T0SE: TMR0 Source Edge Select bit
         1 = Increment on high-to-low transition on RA4/T0CKI pin
         0 = Increment on low-to-high transition on RA4/T0CKI pin
     bit 3 PSA: Prescaler Assignment bit
         1 = Prescaler is assigned to the WDT
         0 = Prescaler is assigned to the Timer0 module
     bit 2-0 PS2:PS0: Prescaler Rate Select bits
     Bit Value     TMR0 Rate     WDT Rate
     PS2-PS0
     000           1 : 2         1 : 1
     001           1 : 4         1 : 2
     010           1 : 8         1 : 4
     011           1 : 16        1 : 8
     100           1 : 32        1 : 16
     101           1 : 64        1 : 32
     110           1 : 128       1 : 64
     111           1 : 256       1 : 128
*/
     //INTCON = 0b11000000;
     //OPTION_REG = 0x00;// select HS Oscillator Source clock for Timer0
     TRISB      =0x00000001; // RB0 's Digital input
     OPTION_REG =0x00 ;      // bit 7 RBPU: PORTB Pull-up Enable bit
                             // bit 6 INTEDG: Interrupt Edge Select bit: Falling
     INTE_bit = 1;           // Enable external interrupt on RB0
     INTF_bit = 0;           // Clear Flag external interrupt

     /*
     INTCON: Interrupt control Register
     GIE  PEIE  TMR0IE  INTE  RBIE  TMR0IF  INTF  RBIF
     bit7                                         bit0
     bit 7 GIE: Global Interrupt Enable bit
         1 = Enables all unmasked interrupts
         0 = Disables all interrupts
     bit 6 PEIE: Peripheral Interrupt Enable bit
         1 = Enables all unmasked peripheral interrupts
         0 = Disables all peripheral interrupts
     bit 5 TMR0IE: TMR0 Overflow Interrupt Enable bit
         1 = Enables the TMR0 interrupt
         0 = Disables the TMR0 interrupt
     bit 4 INTE: RB0/INT External Interrupt Enable bit
         1 = Enables the RB0/INT external interrupt
         0 = Disables the RB0/INT external interrupt
     bit 3 RBIE: RB Port Change Interrupt Enable bit
         1 = Enables the RB port change interrupt
         0 = Disables the RB port change interrupt
     bit 2 TMR0IF: TMR0 Overflow Interrupt Flag bit
         1 = TMR0 register has overflowed (must be cleared in software)
         0 = TMR0 register did not overflow
     bit 1 INTF: RB0/INT External Interrupt Flag bit
         1 = The RB0/INT external interrupt occurred (must be cleared in software)
         0 = The RB0/INT external interrupt did not occur
     bit 0 RBIF: RB Port Change Interrupt Flag bit
         1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to set
         the bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared
         (must be cleared in software).
         0 = None of the RB7:RB4 pins have changed state
     */
     
     INTCON = 0b11000000;         //Enable Global interrupt(GIE) and Peripheral Interrupt (PIE)
     T1CON   = 1;                 // Enable Timer1-16 bit
     PIR1.TMR1IF = 0;             // Clear Timer1 interrupt flag
     PIE1.TMR1IE = 1;             // Enable Timer1 interrupt
     T1CKPS0_bit = 1;             // Select prescaler for Timer1 is 1:1
     T1CkPS1_bit = 1;
    
     TMR1H       =0xFB;
     TMR1L       =0xFF;
     
     /*PS0_bit = 0;            //Set Source clock 1:8, interrupt each 16ms
     PS1_bit = 0;
     PS2_bit = 1;
     TMR0 = 0x00;
     TMR0IE_bit = 1;             // Enable TMRO interrupt*/

     cnt = 0;
     Cnt_Timer0 = 0;
     Segment_DRIVE = 1;
     i = 0;
     USART_Display = 0;
     
     UART1_Init(9600);
     Delay_ms(100);                  // Wait for UART module to stabilize
     UART1_Write_Text("Start");
     
     while(1){

         if( USART_Display){
             ByteToStr(cnt,txt);
             UART1_Write_Text(txt);
             USART_Display = 0;
         }
         switch(Segment_DRIVE){

             case 0:
                 i =SevenSegment_DATA[cnt%10];  //tranh hien tuong bong ma, dua cac gia tri vao bien dem i
                 PORTA = SevenSegment_DRIVE[5];
                 PORTD = i;

                 break;
             case 1:
                 i = SevenSegment_DATA[cnt/10];
                 PORTA = SevenSegment_DRIVE[4];
                 PORTD = i;
                 break;
         }




     }
 }
 #elif (TEST_MODULE ==53)
 
/*******************************************************************************
                           Define Included Header File
*******************************************************************************/
 
#include "RFRemoteDecode.h"
 
 
/*******************************************************************************
                           Define Global Variable
 ******************************************************************************/
 unsigned short Tmr1_Cnt ;                              //Timer1 overflow couter
 unsigned int Tmr0_Cnt ;                              //Timer0 overflow couter
 unsigned short Tmr0_Cnt1;                            // Count for Learning code windows
 unsigned int HighTickCounter ;                          // High level of Signal
 unsigned int TempHTC[10];                                //Store HighTickCouter
 unsigned int TempFiveLow;
 unsigned int TempOneLow;
 unsigned short TempCheck;
 unsigned int TempHTC1;
 unsigned int LowTickCounter  ;                            //Low level of Signal
 unsigned short CntFrame  ;                                  // Count Good Frame
 _RFRemoteDecode_State  State ;                            // Define State of machine
 unsigned short SyncBitCouter;                     // Couter number of Sync bit in timing windows which controled by Timer1( 500ms)
 
 bit Detect31aPulseFlag  ;                // Flag Detect 31a Pulse
 bit Detect1aPulseFlag    ;               // Flag Detect 1a Pulse
 bit DetectSyncBit       ;                // Flag Detect sync bit
 bit EndOfTimingWindows ;                 //Time out 500ms
 bit SyncBitCouter1 ;
 //bit EEPROM_Status ;                      // Check data in EEPROM
 bit LearnCodeEvent ;  //flag of learing code, by press push-button
 bit j, k ;
 
 unsigned short RFReceiverBuffer[12];                // Buffer for addr and data
 unsigned short RFReceiverBufferCounter ;     // Counter Number of Bit to Buffer
 
 unsigned int       TIME_1a_LOW;
 unsigned int       TIME_1a_HIGH;
 unsigned int       TIME_3a_LOW;
 unsigned int       TIME_3a_HIGH;
 unsigned int       TIME_31a_LOW;
 unsigned int       TIME_31a_HIGH ;
 unsigned short i;
 unsigned int HTC[3] ;
 
 unsigned long      RFRemoteAddrCode;
 unsigned int       RFRemoteDatCode ;
 
 unsigned short     EEPROM_Codes_Cnt;
 unsigned short     Cnt;

 
 unsigned short     CodeIndex[5];

 
 _Learningmode     LearnMode;// select learing code modes
 
 ///char txt[8];
 char txt1[8];
 
 
 
/*******************************************************************************
                           Define Interrupt Function
*******************************************************************************/
 void interrupt(void){

     if(TMR0IF_bit){
         //RC1_bit =~ RC1_bit;
         //Tmr0_Cnt++;
         //if( Tmr0_Cnt==5) j=0;
         if (State == RFRemoteDecode_Detect_Min_High_Pulse){
             Tmr0_Cnt++;
             Tmr0_Cnt1++;
             //RC5 flash 5Hz at here
             if(Tmr0_Cnt >= ONE_HUNDREDnFITTY){        // Flashed RC0_pin after 500ms
                 //RC2_bit =~RC2_bit;
                 RC5_bit = ~ RC5_bit;
                 Tmr0_Cnt = 0;
                 EndOfTimingWindows = 1;
             }
             if(Tmr0_Cnt1 >= FOUR_SECOND){          // 4s Learning Windowns break here
             
                 State =  RFRemoteDecode_Detect_Sync_Bit ;
                 Tmr0_cnt1 = 0;
                 LearnCodeEvent = 0;
             }

             
         TMR0 = 0x00;
         }
         else if( State == RFRemoteDecode_Process_Button ){
         
             Tmr0_cnt++;
             // Turn on Led for 2, 4, 6, 8 second

             switch (Tmr0_cnt){
                 case TWO_SECOND :
                     RC4_bit = 1;
                     LearnMode = SingleONOFF;
                     break;
                 case FOUR_SECOND :
                     RC4_bit = 0;
                     LearnMode = AllON ;
                     break;
                 case SIX_SECOND :
                     RC4_bit = 1;
                     LearnMode = AllOFF;
                     break;
                 case EIGHT_SECOND :
                     RC4_bit = 0;
                     LearnMode = Clearance;
                     break;
             }
         }
         else{
             Tmr0_Cnt++;
             if( Tmr0_Cnt == 6){ // auto reset after 150ms
                 Tmr0_Cnt = 0;
                 j=0;
             }
         }

         TMR0IF_bit = 0;
     }
    if( PIR1.TMR1IF){           // Select Timer0 overload Interrupt

         Tmr1_Cnt++;
         //RC3_bit=~ RC3_bit;
         TMR1H = 0x00;
         TMR1L = 0x00;
         PIR1.TMR1IF = 0;
     }
     if(INTF_bit){
         if(State == RFRemoteDecode_Detect_Min_High_Pulse ||
            (State == RFRemoteDecode_Detect_Sync_Bit) ){       //50-100us
             //RC4_bit = ~ RC4_bit;
             /*RC1_bit = 1;*/
             if(RB0_bit == 0){                         //Falling Event Interrupt
                 /*
                 Detect 4a pulse
                 */
                 //Enable Timer0 Interrupt
                 HighTickCounter = (unsigned int )(TMR1L | (TMR1H << 8));
                 TMR1L = 0;
                 TMR1H = 0;
                 if( (HighTickCounter > 0 )&&(HighTickCounter < 2048) &&(Tmr1_Cnt==0)/*&& (HighTickCounter!=0)*/){
                 /*
                 To ensure that 4a pulse appear before 124a pulse
                 */
                     //RC0_bit=~RC0_bit; // Debug
                     Detect1aPulseFlag =1 ;
                 }
                 else{
                     Detect1aPulseFlag = 0;
                     Tmr1_Cnt =0;
                     //HighTickCounter = 0;
                 }
                 INTEDG_bit = 1;                           // Set rising trigged
             }
             // End of Falling Event Interrupt
             else {                                    // Rising Event Interrupt
                 //RC3_bit  =1;
                 /*
                 Detect 124a pulse
                 */
                 //Disable Timer0 Interrupt
                 LowTickCounter = (TMR1L | (TMR1H << 8)) ;          //Get value of timer1 register
                 TMR1L = 0;
                 TMR1H = 0;
                 
                 TempFiveLow = HighTickCounter <<5;
                 TempOneLow  = HighTickCounter <<3;              //bad remote, TempOneLow is higher.
                 if((LowTickCounter >= ((TempFiveLow)-(TempOneLow))) &&
                    (LowTickCounter <=  (TempFiveLow)+ (TempOneLow)) &&
                    (Detect1aPulseFlag) && (Tmr1_Cnt ==0) && (LowTickCounter!=0)){
                     //RC0_bit=0;
                 /*
                 To ensure that 4a pulse appear before 124a pulse
                 */
                     //RC2_bit=~RC2_bit; // Debug
                     if(State == RFRemoteDecode_Detect_Min_High_Pulse){
                         DetectSyncBit = 1;
                         
                         if(SyncBitCouter <=2){
                             *(HTC + SyncBitCouter) = HighTickCounter;
                         }
                         SyncBitCouter++;
                         //RC0_bit = ~ RC0_bit;
                         //RC2_bit = ~ RC2_bit;
                     }
                     if(State == RFRemoteDecode_Detect_Sync_Bit){
                         SyncBitCouter1 = 1;
                         //RC0_bit = ~RC0_bit;
                         //RC1_bit = ~ RC1_bit;
                     }
                 }
                 else {
                     LowTickCounter = 0;
                     HighTickCounter = 0;

                 }
                 //Detect31aPulseFlag = 0;
                 Detect1aPulseFlag = 0;             // Trap Cumulative Error
                 Tmr1_Cnt = 0;             //Clear for starting new sension
                 INTEDG_bit = 0;                          // Set Falling Trigged
                 //RC3_bit = 0;
             }

         }
         // End of State " RFRemoteDecode_Detect_Min_High_Pulse"

/*******************************************************************************
*******************************************************************************/
         if(State == RFRemoteDecode_Detect_AddrnDat)    //70us *24 = 1680us
         {
             //RC2_bit = ~RC2_bit;

             if(RB0_bit == 0){                         //Falling Event Interrupt
                 HighTickCounter = (unsigned int )(TMR1L | (TMR1H << 8));
                 TMR1L = 0;
                 TMR1H = 0;
                 INTEDG_bit = 1;                           // Set rising trigged

             }
             // End of Falling Event Interupt
             else {

                 LowTickCounter = (TMR1L | (TMR1H << 8)) ;          //Get value of timer1 register  //6us
                 TMR1L = 0;
                 TMR1H = 0;
                 if (( TIME_1a_LOW     <= HighTickCounter )  &&
                     ( HighTickCounter <= TIME_1a_HIGH    )  &&
                     ( TIME_3a_LOW     <= LowTickCounter  )  &&
                     ( LowTickCounter  <= TIME_3a_HIGH    )  ){
                     //Detect High 4a pulse and low 12a pulse
                     //RC3_bit = ~RC3_bit;
                     //RC2_bit = ~RC2_bit;
                     //RC2_bit =0;
                     RFReceiverBuffer[RFReceiverBufferCounter >> 3] |= 0b0001 << (RFReceiverBufferCounter & 0x07);
                     RFReceiverBufferCounter += 4;
                     HighTickCounter = 0;
                     LowTickCounter = 0;
                 }
                 else if((TIME_3a_LOW     <= HighTickCounter ) &&
                        ( HighTickCounter <= TIME_3a_HIGH    ) &&
                        ( TIME_1a_LOW     <= LowTickCounter  ) &&
                        ( LowTickCounter  <= TIME_1a_HIGH)   ) {
                        //RC3_bit=~RC3_bit;
                     // Detect High 12a pulse and low 4a pulse
                     RFReceiverBuffer[RFReceiverBufferCounter >> 3] |= 0b0111 << (RFReceiverBufferCounter & 0x07);
                     RFReceiverBufferCounter += 4;
                     HighTickCounter = 0;
                     LowTickCounter = 0;
                 }
                 else{
                 // Goto  State of Detect_Sync_Bit
                     HighTickCounter = 0;
                     LowTickCounter = 0;
                     RFReceiverBufferCounter = 0;
                     Tmr1_Cnt = 0;
                     State = RFRemoteDecode_Detect_Sync_Bit ;
                     TMR0IE_bit = 1;

                     //RC0_bit = ~RC0_bit;

                 }
                 RFReceiverBuffer[(RFReceiverBufferCounter >> 3) + 1] = 0x00 ;
                 INTEDG_bit = 0;                 //Set falling trigged interrupt
             }
             if(RFReceiverBufferCounter >= 96){
                 CntFrame = 1;
                 //RC5_bit = 1;
             }
             //RC0_bit = 0;
             //RC1_bit = 0;
             // End of Rising Event Interupt
         }
         INTF_bit = 0;
     }
 }
/*******************************************************************************
                               Main Program
*******************************************************************************/
 void main(void){
 
     UART1_Init(9600);
     Delay_ms(100);                  // Wait for UART module to stabilize
     UART1_Write_Text("Start");

     Tmr1_Cnt          = 0;
     Tmr0_Cnt          = 0;
     Tmr0_Cnt1         = 0;
     HighTickCounter   = 0;                         // High level of Signal
     LowTickCounter    = 0;                           //Low level of Signal
     CntFrame          = 0;                             // Count Good Frame
     SyncBitCouter     = 0;
                                                  
     TempFiveLow = 0;
     TempOneLow = 0;

     Detect31aPulseFlag  = 0 ;
     Detect1aPulseFlag   = 0 ;
     DetectSyncBit       = 0 ;
     EndOfTimingWindows  = 0 ;
     SyncBitCouter1      = 0 ;
     j                   = 0 ;
     k                   = 0 ;
     
     TIME_1a_HIGH        = 0;
     TIME_1a_LOW         = 0;
     TIME_3a_HIGH        = 0;
     TIME_3a_LOW         = 0;
     TIME_31a_HIGH       = 0;
     TIME_31a_LOW        = 0;
     
     LearnCodeEvent      = 0;
     LearnMode           = 5 ;// (singleonoff = 0, AllON =1, AllOFF =2, Sleep=3, Clearance =4)
     Cnt                 = 0; // Number of codes which equals Alpha
 
 /******************************************************************************
                  Config RC0-RC5 as Debuger LED, all off when  start
*******************************************************************************/
     TRISC = 0b00000000;
     PORTC = 0x00;
     /*
     RC0_bit: Timer0 interrupt signalling
     RC1_bit:
     RC2_bit: Detect 1 syncbit
     RC3_bit: Timer1 interrupt signalling
     RC4_bit : Check data in EEPROM
     */
     for( RFReceiverBufferCounter = 0; RFReceiverBufferCounter < 12 ;RFReceiverBufferCounter ++){
          RFReceiverBuffer [RFReceiverBufferCounter] = 0x00;
     }
     RFReceiverBufferCounter = 0;
     /*for( i = 0; i< 5; i++){
        CodeIndex[i] = 0;
     }*/
     /* Clear all data in receiver's buffer */
     //RC3_bit = 1;
     EEPROM_Codes_Cnt = EEPROM_Read(0x00) ;
     if(EEPROM_Codes_Cnt == 0xFF){         // Nothing
         EEPROM_Codes_Cnt=0;
         //RC4_bit = 1;
         State   = /*RFRemoteDecode_Detect_Min_High_Pulse*/RFRemoteDecode_Detect_Sync_Bit;
     }
     else{
         State   = RFRemoteDecode_Detect_Sync_Bit;
         
         for(i = 0; i<= EEPROM_Codes_Cnt; i++){
         
             TempHTC[i] = EEPROM_Read(0x01 + ((EEPROM_Codes_Cnt -1 )<<3));
             TempHTC[i] = TempHTC[i] + (EEPROM_Read(0x02 + ((EEPROM_Codes_Cnt-1)<<3))<<8);
         
         }

     }
     
     /**************************************************************************
     EEPROM map
     0x00: Counted number of learned frames, 1-31
     0x01->0x09: for comple frame
         0x01-0x02: Storageed alpha, next alpha: +8
         0x03-0x08: storaged Address and dat, next Address and dat, + 8
              0x03->0x06: Address
              0x07-> 0x08: dat
         0x09       ;Type of learning code.
     PIC16F877A : 256 Byte EEPROM-> Receiver able to be storaged (256-1)/8= 31 codes
     **************************************************************************/
     
 /*  OPTION_REG Register
     bit 7 RBPU: PORTB Pull-up Enable bit
         1 = PORTB pull-ups are disabled
         0 = PORTB pull-ups are enabled by individual port latch values
     bit 6 INTEDG: Interrupt Edge Select bit
         1 = Interrupt on rising edge of RB0/INT pin
         0 = Interrupt on falling edge of RB0/INT pin
     bit 5 T0CS: TMR0 Clock Source Select bit
         1 = Transition on RA4/T0CKI pin
         0 = Internal instruction cycle clock (CLKO)
     bit 4 T0SE: TMR0 Source Edge Select bit
         1 = Increment on high-to-low transition on RA4/T0CKI pin
         0 = Increment on low-to-high transition on RA4/T0CKI pin
     bit 3 PSA: Prescaler Assignment bit
         1 = Prescaler is assigned to the WDT
         0 = Prescaler is assigned to the Timer0 module
     bit 2-0 PS2:PS0: Prescaler Rate Select bits
     Bit Value     TMR0 Rate     WDT Rate
     PS2-PS0
     000           1 : 2         1 : 1
     001           1 : 4         1 : 2
     010           1 : 8         1 : 4
     011           1 : 16        1 : 8
     100           1 : 32        1 : 16
     101           1 : 64        1 : 32
     110           1 : 128       1 : 64
     111           1 : 256       1 : 128
 */
 
 /******************************************************************************
                      Configure External Interupt and
             Button for learing code, Button is assigned at RB1
 ******************************************************************************/

     TRISB      =0b00000101; // RB0 and RB2 are Digital input
     OPTION_REG =0b01000000 ;      
                              // bit 7 RBPU: PORTB Pull-up Enable bit
                             // bit 6 INTEDG: Interrupt Edge Select bit: Rising
     INTE_bit = 0;           // Disable external interrupt on RB0
     INTF_bit = 0;           // Clear Flag external interrupt
 /*
     INTCON: Interrupt control Register
     GIE  PEIE  TMR0IE  INTE  RBIE  TMR0IF  INTF  RBIF
     bit7                                         bit0
     bit 7 GIE: Global Interrupt Enable bit
         1 = Enables all unmasked interrupts
         0 = Disables all interrupts
     bit 6 PEIE: Peripheral Interrupt Enable bit
         1 = Enables all unmasked peripheral interrupts
         0 = Disables all peripheral interrupts
     bit 5 TMR0IE: TMR0 Overflow Interrupt Enable bit
         1 = Enables the TMR0 interrupt
         0 = Disables the TMR0 interrupt
     bit 4 INTE: RB0/INT External Interrupt Enable bit
         1 = Enables the RB0/INT external interrupt
         0 = Disables the RB0/INT external interrupt
     bit 3 RBIE: RB Port Change Interrupt Enable bit
         1 = Enables the RB port change interrupt
         0 = Disables the RB port change interrupt
     bit 2 TMR0IF: TMR0 Overflow Interrupt Flag bit
         1 = TMR0 register has overflowed (must be cleared in software)
         0 = TMR0 register did not overflow
     bit 1 INTF: RB0/INT External Interrupt Flag bit
         1 = The RB0/INT external interrupt occurred (must be cleared in software)
         0 = The RB0/INT external interrupt did not occur
     bit 0 RBIF: RB Port Change Interrupt Flag bit
         1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to set
         the bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared
         (must be cleared in software).
         0 = None of the RB7:RB4 pins have changed state
     */
 /*bit 2-0 PS2:PS0: Prescaler Rate Select bits
     Bit Value     TMR0 Rate     WDT Rate
     PS2-PS0
     000           1 : 2         1 : 1
     001           1 : 4         1 : 2
     010           1 : 8         1 : 4
     011           1 : 16        1 : 8
     100           1 : 32        1 : 16
     101           1 : 64        1 : 32
     110           1 : 128       1 : 64
     111           1 : 256       1 : 128
 */
 /******************************************************************************
                           Configure TMR0 Interupt, overload after 32,768 ms
 ******************************************************************************/
     PS2_bit = 1;
     PS1_bit = 1;
     PS0_bit = 1;
     TMR0    = 0x00;
     TMR0IE_bit = 0;
     TMR0IF_bit = 0;
 /******************************************************************************
                           Configure Timer1( 16bit) and Timer1 Interrupt
 ******************************************************************************/
     INTCON = 0b11000000;         //Enable Global interrupt(GIE) and Peripheral Interrupt (PIE)
     T1CON   = 1;                 // Enable Timer1-16 bit
     PIR1.TMR1IF = 0;             // Clear Timer1 interrupt flag
     PIE1.TMR1IE = 1;             // Enable Timer1 interrupt
     T1CKPS1_bit = 0;             // Select prescaler for Timer1 is 1:2
     T1CkPS0_bit = 1;

     TMR1H       =0x00;
     TMR1L       =0x00;
     /*T1CKPS1:T1CKPS0
     11 = 1:8 prescale value
     10 = 1:4 prescale value
     01 = 1:2 prescale value
     00 = 1:1 prescale value*/
     RC0_bit = 1;// starting
     TMR0IE_bit = 1;
     INTE_bit = 1; // Enable External Interrupt
     INTEDG_bit = 1;// Falling
     
     while(1){
     
         switch ( State){
             case (RFRemoteDecode_Detect_Sync_Bit) :        //case 0
                 if( SyncBitCouter1 && ((EEPROM_Codes_Cnt != 0)||(LearnCodeEvent == 1) ) ){
                     // if not address and dat in eeprom, must press button to learn code
                     SyncBitCouter1 =0;

                     RC0_bit =~ RC0_bit;
                     // Compare HighTickCouter with alpha which storaged in EEPROM
                     // Calculate TIMe1a low and high, Time3a low and high
                     // and calculate here 's OK  because |-| =(180-200us)ok
                     if(LearnCodeEvent ==0 ){
                         //RC3_bit = 1;
                         TempHTC1 = HighTickCounter + (HighTickCounter >>3);//50us

                         TempOneLow =  TempHTC1 >> 2;
                         TIME_1a_LOW  = TempHTC1 - (TempOneLow); // 0.75
                         TIME_1a_HIGH = TempHTC1 + (TempOneLow); // 1.25

                         TIME_3a_LOW  = (TIME_1a_LOW <<2) - TIME_1a_LOW;
                         TIME_3a_HIGH = (TIME_1a_HIGH <<2) - TIME_1a_HIGH;    //50us
                         
                         //RC3_bit = ~RC3_bit;
                     }

                     // set timer0 to proces button on the transmitter
                     State =RFRemoteDecode_Detect_AddrnDat;
                     /*EndOfTimingWindows = 0;
                     SyncBitCouter = 0;*/
                 }
                 if( Button( &PORTB, 2, 1, PRESS)){  // When Press RB1_pin, active State's 0.
                                                     //Normal State of it 's 1, "1' a debounce period in milliseconds

                     RC5_bit =  ~RC5_bit;     // Lamp will be switch ON of OFF
                     INTE_bit = 0 ;        // Disable external interrupt
                     TMR0    = 0;    //Clear Timer0 register
                     TMR0IE_bit  = 1;    // Enable timer0 in terrupt
                     Tmr0_Cnt = 0;   // clear overload variable of timer 0
                     State  =  RFRemoteDecode_Process_Button;
                 }
                 break;
             case (RFRemoteDecode_Detect_Min_High_Pulse) :  //case 1     45us
                 //RC1_bit = ~RC1_bit;
                 if(DetectSyncBit /*EndOfTimingWindows*/ /*&&((EEPROM_Codes_Cnt != 0)||(LearnCodeEvent == 1) )*/){                // Get HighTickCouter Exactly
                     //RC1_bit = ~RC1_bit;
                     if(EndOfTimingWindows){
                     //RC1_bit = 1;
                     //RC1_bit = ~RC1_bit;
                         if((SyncBitCouter >= 3)  && (abs(HTC[0] - HTC[1]) <=10)&& (abs(HTC[2] - HTC[1]) <=10) /*&& (HighTickCounter > 0) &&(HighTickCounter < 2048)*/ ){    //bug here
                             GIE_bit = 0;
                             //RC0_bit = ~RC0_bit;
                             TMR0IE_bit = 0;// Disable tmr0 interrupt
                             //RC4_bit = ~RC4_bit;                           //320ms
                             if( LearnCodeEvent){                           // implement: 4,2ms
                                 RC1_bit = 1;
                                 //GIE_bit = 0;       // Disable all interrupt, The value of tmr0, tmr1 are not reset 0
                                 //RC3_bit = 1;
                                 TempHTC[EEPROM_Codes_Cnt] = HighTickCounter + (HighTickCounter >>3);//65us
                                 
                                 TIME_1a_LOW  = TempHTC[EEPROM_Codes_Cnt] - (TempHTC[EEPROM_Codes_Cnt] >> 2); // 0.75
                                 TIME_1a_HIGH = TempHTC[EEPROM_Codes_Cnt] + (TempHTC[EEPROM_Codes_Cnt] >> 2); // 1.25        65us

                                 TIME_3a_LOW  = (TIME_1a_LOW <<2) - TIME_1a_LOW;
                                 TIME_3a_HIGH = (TIME_1a_HIGH <<2) - TIME_1a_HIGH;

                                 TempCheck =  TempHTC[EEPROM_Codes_Cnt] >> 8 ;  //10us
                                 //RC1_bit = 1;
                                 TempOneLow = EEPROM_Codes_Cnt +(EEPROM_Codes_Cnt<<3);
                                 EEPROM_Write( (0x02 + (/*EEPROM_Codes_Cnt<<3*/TempOneLow)), ((unsigned short )/*(TempHTC[EEPROM_Codes_Cnt] >> 8  )*/ TempCheck));       //4ms  , TempCheck -~4ms

                                 EEPROM_Write( (0x01 + (/*EEPROM_Codes_Cnt<<3*/TempOneLow)), ((unsigned short )(TempHTC[EEPROM_Codes_Cnt]       )));       //30us

                                 State = RFRemoteDecode_Detect_Sync_Bit;
                                 //RC1_bit = 0;
                             }

                             *(HTC)   = 0;
                             *(HTC+1) = 0;
                             *(HTC+2) = 0;
                             GIE_bit = 1;
                         }
                         SyncBitCouter = 0;
                         //Tmr0_Cnt = 0;
                     }
                     EndOfTimingWindows = 0;
                 }
                 DetectSyncBit = 0;

                 break;
             case (RFRemoteDecode_Detect_AddrnDat) :        //case 2
                 // may be calculate Time1a low and high, time 3a low and high here
                 EndOfTimingWindows = 0;
                 SyncBitCouter = 0;
                 if(CntFrame){                 //3200us
                     //RC1_bit = 1;
                     //GIE_bit = 0;
                     INTE_bit = 0;
                     PIE1.TMR1IE = 0;
                     /*RC1_bit = 1;
                     ByteToStr(EEPROM_Codes_Cnt, txt1);
                     UART1_Write_Text(txt1);
                     RC1_bit = 0;*/
                     Delay_ms(2);

                     RFRemoteAddrCode= RFRemoteDecode_GetAddr(RFReceiverBuffer);
                     RFRemoteDatCode = RFRemoteDecode_GetData(RFReceiverBuffer);
                     for( RFReceiverBufferCounter = 0; RFReceiverBufferCounter < 12 ;RFReceiverBufferCounter ++){
                          RFReceiverBuffer [RFReceiverBufferCounter] = 0x00;
                      }
                      RFReceiverBufferCounter = 0;
                      // Clear buffer and buffercouter
                     CntFrame = 0;
                     RC2_bit = ~RC2_bit;
                     
                         for(i = 1; i <= EEPROM_Codes_Cnt; i++){
                             TempOneLow = i-1+((i-1)<<3);
                             if((EEPROM_Read (0x03 + /*((EEPROM_Codes_Cnt i-1)<<3)*/TempOneLow)==(unsigned short )(RFRemoteAddrCode       )) &&
                                (EEPROM_Read (0x04 + /*((EEPROM_Codes_Cnt i-1)<<3)*/TempOneLow)==(unsigned short )(RFRemoteAddrCode >> 8  )) &&
                                (EEPROM_Read (0x05 + /*((EEPROM_Codes_Cnt i-1)<<3)*/TempOneLow)==(unsigned short )(RFRemoteAddrCode >> 16 )) &&
                                (EEPROM_Read (0x06 + /*((EEPROM_Codes_Cnt i-1)<<3)*/TempOneLow)==(unsigned short )(RFRemoteAddrCode >> 24 )) &&
                                (EEPROM_Read (0x07 + /*((EEPROM_Codes_Cnt i-1)<<3)*/TempOneLow)==(unsigned short )(RFRemoteDatCode       ))  &&
                                (EEPROM_Read (0x08 + /*((EEPROM_Codes_Cnt i-1)<<3)*/TempOneLow)==(unsigned short )(RFRemoteDatCode >> 8  )) ){
                                
                                 // Time operation: 200us
                                 TempOneLow = EEPROM_Read (0x09 + /*((EEPROM_Codes_Cnt i-1)<<3)*/TempOneLow) ;
                                 if( TempOneLow == AllON){
                                     RC5_bit = 1;
                                 }
                                 else if( TempOneLow == AllOFF){
                                    RC5_bit = 0;
                                 }
                                 else{
                                     k = 1;
                                     if(j==0){
                                         RC5_bit=~RC5_bit;
                                         Tmr0_Cnt = 0;
                                         TMR0 = 0;
                                         j=1;
                                     }
                                     //RC5_bit=~RC5_bit;
                                     else{
                                         Tmr0_Cnt = 0;
                                         TMR0 = 0;
                                     }
                                 }
                                 /*k = 1;
                                 if(j==0){
                                     RC5_bit=~RC5_bit;
                                     Tmr0_Cnt = 0;
                                     TMR0 = 0;
                                     j=1;
                                 }
                                 //RC5_bit=~RC5_bit;
                                 else{
                                     Tmr0_Cnt = 0;
                                     TMR0 = 0;
                                 }*/
                                 break;
                             }
                                
                         }
                         if((k) /*|| ((!LearnCodeEvent) && (!k))*/  ){
                             //GIE_bit = 1;
                             INTE_bit = 1;
                             PIE1.TMR1IE = 1;
                             State = RFRemoteDecode_Detect_Sync_Bit;
                             k=0;
                             LearnCodeEvent = 0;
                         }
                         else{
                             if(LearnCodeEvent){
                                 State =RFRemoteDecode_Establish_Code ;
                                 LearnCodeEvent = 0;
                             }
                             else{
                                 INTE_bit = 1;
                                 PIE1.TMR1IE = 1;
                                 State = RFRemoteDecode_Detect_Sync_Bit;
                                 //k=0;
                             }
                         }
                 }
                 break;
             case (RFRemoteDecode_Process_Button) :         //case 3
             while(1){

                      if (Button( &PORTB, 2, 1, RELEASE )){    // Release Button
                          Rc4_bit = ~RC4_bit;
                          RC5_bit = ~ RC5_bit ;            // Switch ON/OFF Lamp
                          //TMR0IE_bit = 0; // disable timer0 interrupt
                          // Create Waiting time 2s to capture new code, using timer0
                          // after this 2 second, if nothing code 's captured, receiver will be go to RFRemoteDecode_Detect_Sync_Bit state
                          if((Tmr0_Cnt >= TWO_SECOND) &&(Tmr0_Cnt < EIGHT_SECOND) ){
                              //GP1_bit =~ GP1_bit ;
                              // Set 3s learning code windows time here, after that time, if no valid code come from, pointer  program travel to
                              // RFRemoteDecode_Detect_Sync_Bit and Using Timer0 
                              // In this 3s, LED of this chanel will be flashing at 5Hz 8/30/2013 ToanRV
                              LearnCodeEvent = 1;           // Learing code mode
                              
                              INTE_bit = 1 ;        // enable external interrupt
                              TMR1H       =0x00;    // reset timer1 register
                              TMR1L       =0x00;
                              State = RFRemoteDecode_Detect_Min_High_Pulse ; //
                              TMR0 = 0;
                              Tmr0_Cnt1 = 0;
                              
                          }
                          else if(  Tmr0_cnt >= EIGHT_SECOND){
                              // clear all code
                              EEPROM_Codes_Cnt = 0;
                              EEPROM_Write(0x00, 0); // eeprom has code if 0x00 is not "0".
                              State = RFRemoteDecode_Detect_Sync_Bit;
                          }
                          else{
                              State =  RFRemoteDecode_Detect_Sync_Bit;      // time <2s, turn on/off lamp and no go to learn code
                          }
                          
                          INTE_bit = 1 ;        // enable external interrupt
                          TMR1H    =0x00;    // reset timer1 register
                          TMR1L    =0x00;
                          Tmr0_Cnt = 0;
                          break;
                      }
                  }
                  EndOfTimingWindows = 0;
                  SyncBitCouter = 0;

                 break;
             case (RFRemoteDecode_Establish_Code) :         //case 4
                 EndOfTimingWindows = 0;
                 SyncBitCouter = 0;
                 //RC4_bit = ~RC4_bit ;
                 //RC1_bit = 1;
                 TempOneLow =  EEPROM_Codes_Cnt+ (EEPROM_Codes_Cnt<<3) ;
                 EEPROM_Write( (0x03 + (/*EEPROM_Codes_Cnt<<3*/TempOneLow)), ((unsigned short )(RFRemoteAddrCode       )));
                 EEPROM_Write( (0x04 + (/*EEPROM_Codes_Cnt<<3*/TempOneLow)), ((unsigned short )(RFRemoteAddrCode >> 8  )));
                 EEPROM_Write( (0x05 + (/*EEPROM_Codes_Cnt<<3*/TempOneLow)), ((unsigned short )(RFRemoteAddrCode >> 16 )));
                 EEPROM_Write( (0x06 + (/*EEPROM_Codes_Cnt<<3*/TempOneLow)), ((unsigned short )(RFRemoteAddrCode >> 24 )));

                 EEPROM_Write( (0x07 + (/*EEPROM_Codes_Cnt<<3*/TempOneLow)), ((unsigned short )(RFRemoteDatCode       )));
                 EEPROM_Write( (0x08 + (/*EEPROM_Codes_Cnt<<3*/TempOneLow)), ((unsigned short )(RFRemoteDatCode >> 8  )));
                 EEPROM_Write( (0x09 + (/*EEPROM_Codes_Cnt<<3*/TempOneLow)), ((unsigned short )(LearnMode )));
                 //RC1_bit = 0;
                 // 6 EEPROM_Write: 20ms
                 LearnMode = 5; //reset learnmde
                 EEPROM_Codes_Cnt =EEPROM_Codes_Cnt + 1 ;
                 EEPROM_Write(0x00, EEPROM_Codes_Cnt);

                 //RC0_bit = 1;


                 State = RFRemoteDecode_Detect_Sync_Bit;
                 //GIE_bit = 1;
                 TMR0        =0;
                 TMR1H       =0x00;
                 TMR1L       =0x00;
                 TMR0IE_bit  = 1;                   //Why ?
                 INTEDG_bit = 0;// Falling
                 Tmr1_Cnt    = 0;
                 //INTE_bit    = 1;
                 //Delay_ms(30);
                  
                 //GIE_bit     =1;         //Enable all interrupt
                 INTE_bit = 1;
                 PIE1.TMR1IE = 1;
                 break;

             case (RFRemoteDecode_Control_Actuators ):      // case 5
                 break;
         }

     
     }
 }
 
 #elif( TEST_MODULE == 6)
 
 
 #define    PRESS      0
 #define    RELEASE    1

 #define    MENU    RB4_bit
 #define    UP      RB1_bit
 #define    DOWN    RB2_bit
 #define    SET     RB3_bit
 
 // LCD module connections
 sbit LCD_RS at RA1_bit;
 sbit LCD_EN at RA3_bit;
 sbit LCD_D4 at RD4_bit;
 sbit LCD_D5 at RD5_bit;
 sbit LCD_D6 at RD6_bit;
 sbit LCD_D7 at RD7_bit;

 sbit LCD_RS_Direction at TRISA1_bit;
 sbit LCD_EN_Direction at TRISA3_bit;
 sbit LCD_D4_Direction at TRISD4_bit;
 sbit LCD_D5_Direction at TRISD5_bit;
 sbit LCD_D6_Direction at TRISD6_bit;
 sbit LCD_D7_Direction at TRISD7_bit;
 // End LCD module connections
     

 typedef enum FSM_State{ FSM_DISPLAY, FSM_CONFIG};
 
 /****************************************************************************
                           Define Global Variable
 *****************************************************************************/
 RTC_Time p1;              // Time data
 unsigned short State ;    // FSM
 bit Flag_RB4_PRESS  ;     // Interrupt flag in RB4
 bit DS1307_DATA     ;     // Check time data in DS1307
 unsigned short cnt ;      // Used to get time data from Button
 
/****************************************************************************
                           Define Function prototye
*****************************************************************************/

void Get_Char_Button( unsigned short Time_Threshold);
void LCD_Make_TimeFormat();

/****************************************************************************
                           Define Interrupt Function
*****************************************************************************/
void interrupt (void){

    if( RBIF_bit){
        Flag_RB4_PRESS = 1;
        RBIF_bit = 0;
    }
}
 
void main(void){
 
     // Config LCD connection
     TRISA1_bit = 0;
     TRISA2_bit = 0;
     TRISA3_bit = 0;
     TRISD4_bit = 0;
     TRISD5_bit = 0;
     TRISD6_bit = 0;
     TRISD7_bit = 0;
     ADCON1 = 0x06;             //All pin of PORTA are Digital I/O
     
     // Config Button Menu,up, set, down are as input and the default status of these are high logic
     TRISB = 0b00011110 ;       // 4 lower  bits are set as input
     OPTION_REG = 0x00 ;        //Enable pull-up resistor in PORTB
     INTCON = 0b10001000;        // Enable RB4 interrupt on change,
     /*
     INTCON: Interrupt control Register
     GIE  PEIE  TMR0IE  INTE  RBIE  TMR0IF  INTF  RBIF
     bit7                                         bit0
     bit 7 GIE: Global Interrupt Enable bit
         1 = Enables all unmasked interrupts
         0 = Disables all interrupts
     bit 6 PEIE: Peripheral Interrupt Enable bit
         1 = Enables all unmasked peripheral interrupts
         0 = Disables all peripheral interrupts
     bit 5 TMR0IE: TMR0 Overflow Interrupt Enable bit
         1 = Enables the TMR0 interrupt
         0 = Disables the TMR0 interrupt
     bit 4 INTE: RB0/INT External Interrupt Enable bit
         1 = Enables the RB0/INT external interrupt
         0 = Disables the RB0/INT external interrupt
     bit 3 RBIE: RB Port Change Interrupt Enable bit
         1 = Enables the RB port change interrupt
         0 = Disables the RB port change interrupt
     bit 2 TMR0IF: TMR0 Overflow Interrupt Flag bit
         1 = TMR0 register has overflowed (must be cleared in software)
         0 = TMR0 register did not overflow
     bit 1 INTF: RB0/INT External Interrupt Flag bit
         1 = The RB0/INT external interrupt occurred (must be cleared in software)
         0 = The RB0/INT external interrupt did not occur
     bit 0 RBIF: RB Port Change Interrupt Flag bit
         1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to set
         the bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared
         (must be cleared in software).
         0 = None of the RB7:RB4 pins have changed state
     */
     
     Flag_RB4_PRESS  = 0;
     cnt = 0;
 
     Lcd_Init();                // Initialize LCD
     Lcd_Cmd(_LCD_CLEAR);       // Clear LCD display
     Lcd_Cmd(_LCD_CURSOR_OFF);  // Turn cursor off
     LCD_Make_TimeFormat();


     DS1307_Init();
     State = FSM_DISPLAY;
     if((p1.sec ==0x00) &&(p1.min ==0x00) && (p1.hour ==0x00)&& (p1.week_day ==0x00)&&
        (p1.day ==0x01) &&(p1.month ==0x01) && (p1.year ==0x01))
        
        DS1307_DATA = 0;      // No data in DS1307
     else
         DS1307_DATA = 1;     // Yes data in DS1307
     while (1) {                // Endless loop
     
         switch (state){

             case(FSM_DISPLAY):
             DS1307_GetDateTime(&p1);
             if((!DS1307_DATA) ||(Flag_RB4_PRESS))
                // Not Data in DS1307 or RB0 is pressed.
             {
                 State = FSM_CONFIG;
             }
             else
                 DS1307_LCD_Display_Time(&p1);
             break;
             
             case(FSM_CONFIG):
             
                 Lcd_Cmd(_LCD_CLEAR);       // Clear LCD display
                 Lcd_Out(1,1,"Sec  :");      // Prepare and output static text on LCD
                 while(1){
                     Get_Char_Button(60);
                     if(Button(&PORTB , 3, 1, PRESS)){              // SET_key is press
                         while(Button(&PORTB , 3, 1, PRESS)){;}     // Wait until SET_key is released
                         p1.sec = cnt;
                         cnt = 0;
                         break;
                     }
                 }
                 
                 Lcd_Cmd(_LCD_CLEAR);
                 Lcd_Out(1,1,"Min  :");      // Prepare and output static text on LCD
                 while(1){
                     Get_Char_Button(60);
                     if(Button(&PORTB , 3, 1, PRESS)){              // SET_key is press
                         while(Button(&PORTB , 3, 1, PRESS)){;}     // Wait until SET_key is released
                         p1.min = cnt;
                         cnt = 0;
                         break;
                     }
                 }
                 
                 Lcd_Cmd(_LCD_CLEAR);
                 Lcd_Out(1,1,"Hour :");      // Prepare and output static text on LCD
                 while(1){
                     Get_Char_Button(24);
                     if(Button(&PORTB , 3, 1, PRESS)){              // SET_key is press
                         while(Button(&PORTB , 3, 1, PRESS)){;}     // Wait until SET_key is released
                         p1.hour = cnt;
                         cnt = 0;
                         break;
                     }
                 }
                 
                 Lcd_Cmd(_LCD_CLEAR);
                 Lcd_Out(1,1,"Day  :");      // Prepare and output static text on LCD
                 while(1){
                     Get_Char_Button(31);
                     if(Button(&PORTB , 3, 1, PRESS)){              // SET_key is press
                         while(Button(&PORTB , 3, 1, PRESS)){;}     // Wait until SET_key is released
                         p1.day = cnt;
                         cnt = 0;
                         break;
                     }
                 }
                 
                 Lcd_Cmd(_LCD_CLEAR);
                 Lcd_Out(1,1,"Month :");      // Prepare and output static text on LCD
                 while(1){
                     Get_Char_Button(12);
                     if(Button(&PORTB , 3, 1, PRESS)){              // SET_key is press
                         while(Button(&PORTB , 3, 1, PRESS)){;}     // Wait until SET_key is released
                         p1.month = cnt;
                         cnt = 0;
                         break;
                     }
                 }
                 
                 Lcd_Cmd(_LCD_CLEAR);
                 Lcd_Out(1,1,"Year :");      // Prepare and output static text on LCD
                 while(1){
                     Get_Char_Button(99);
                     if(Button(&PORTB , 3, 1, PRESS)){              // SET_key is press
                         while(Button(&PORTB , 3, 1, PRESS)){;}     // Wait until SET_key is released
                         p1.year = cnt;
                         cnt = 0;
                         break;
                     }
                 }
                 
                 DS1307_SetDateTime(&p1);
                 //Lcd_Cmd(_LCD_CLEAR);
                 //Lcd_Out(1,1,"OK");
                 State = FSM_DISPLAY ;
                 Flag_RB4_PRESS = 0;     // Clear Flag
                 LCD_Make_TimeFormat();
              break;
         }
     }
 }

/****************************************************************************
                           Define  Subfunction
*****************************************************************************/
 void Get_Char_Button( unsigned short Time_Threshold){
 
     if (Button(&PORTB , 2, 1, PRESS)){           // DOWN_Key is press
         while(Button(&PORTB , 2, 1 , PRESS)){
             ;
         }  // Wait until DOWN_Key is released
         //LCD_out(1,1, " YES DOWN");
         cnt--;
         if (cnt == 0){
            cnt = Time_Threshold-1;
         }
         LCD_Chr(1,7,(cnt /10) +48);
         LCD_Chr(1,8,(cnt %10) +48);
     }
     if(Button(&PORTB , 1, 1, PRESS)){              // UP_key is press
         while(Button(&PORTB , 1, 1, PRESS)){
             ;
         }     // Wait until UP_key is released
         cnt++;
         if( cnt == Time_Threshold) {
             cnt = 0;
         }
         LCD_Chr(1,7,(cnt /10) +48);
         LCD_Chr(1,8,(cnt %10) +48);
     }
 }
 
 void LCD_Make_TimeFormat(){
     Lcd_Out(1,1,"Date:");      // Prepare and output static text on LCD
     Lcd_Chr(1,8,'.');
     Lcd_Chr(1,11,'.');
     Lcd_Chr(1,16,'.');
     Lcd_Out(2,1,"Time:");
     Lcd_Chr(2,8,':');
     Lcd_Chr(2,11,':');
     Lcd_Out(1,12,"20");       // start from year 2000
 }

 #elif( TEST_MODULE == 7)
 #define    PRESS      0
 #define    RELEASE    1

 #define    MENU    RB4_bit
 #define    UP      RB1_bit
 #define    DOWN    RB2_bit
 #define    SET     RB3_bit

 typedef enum FSM_State{ FSM_DISPLAY, FSM_CONFIG};
 
 /****************************************************************************
                           Define Global Const
 *****************************************************************************/
 const char SevenSegment_DATA[10]={0xC0,0xF9,0xA4,0xB0,0x99,    // 0 1 2 3 4
                                    0x92,0x82,0xF8,0x80,0x90 };  // 5 6 7 8 9
                   // define constant 0-5 data table, 7segment common anode
 const char SevenSegment_DRIVE[6]= {0x3E, 0x3D, 0x3B, 0x37, 0x2F, 0X1F };
                                   // RA0-Q1 RA1-Q2 RA2-Q3
                                   // RA4-Q1 RA5-Q2 RA5-Q6

 /****************************************************************************
                           Define Global Variable
 *****************************************************************************/
 RTC_Time p1;              // Time data
 unsigned short State ;    // FSM
 bit Flag_RB4_PRESS  ;     // Interrupt flag in RB4
 bit DS1307_DATA     ;     // Check time data in DS1307
 unsigned short cnt ;      // Used to get time data from Button
 unsigned short SelectSegment_Timer;// Select 0->6 7segment
 bit SegmentSixOrTwo ;     //Display 6 7Segment or 2 7Segment(Set time data) in ISR
 bit SelectSegment_TwoDigit;// Display each 2 7segment

/****************************************************************************
                           Define Function prototye
*****************************************************************************/

void SevenSegmnet_Display( unsigned short n, unsigned short NumberSegment);
// Display number which has two digits
void Get_Char_Button_Segment( unsigned short Time_Threshold, unsigned short NumberSegment);
// Get value from button UP, DOWN Key and Display 7segment
void SevenSegmnet_Six_Display(unsigned short sec, unsigned short min, unsigned short hour);
// Display nummber which has 6 digits by 7segment

/****************************************************************************
                           Define Interrupt Function
*****************************************************************************/
void interrupt (void){

    if( RBIF_bit){             // Select RB4 Interrupt On-change
        Flag_RB4_PRESS = 1;    // Set Flag to confirm main program
        RBIF_bit = 0;          // Clear RB4 interrupt flag
    }
    if( TMR0IF_bit){           // Select Timer0 overload Interrupt
    
        if(SegmentSixOrTwo){             // Display sec, hour, min
            SelectSegment_Timer ++;
            if(SelectSegment_Timer ==6){
                SelectSegment_Timer = 0;
            }
            TMR0 = 0x00;
            TMR0IF_bit = 0;
        }
        else{
        //Display sec or min or hour
            SelectSegment_TwoDigit=~ SelectSegment_TwoDigit; // inverse to scan 2 7segment
            TMR0 = 0x00;
            TMR0IF_bit = 0;
        }

    }
}

void main(void){
     
     // Config IO of 7segment
     ADCON1 = 0x06;           // All GPIO as Digital IO
     TRISA  =0b11000000;      // Control PIN as input, RA0->RA5
     PORTA  =0x3F;            // Turn off ALl 7segment anode common
     
     TRISD  =0x00;            //PORTD as output(Datapath of 7segment)
     PORTD  =0x00;            //Turn off all 7segment
     // End of Config IO of 7segment

     // Config Button Menu,up, set, down are as input and the default status of these are high logic
     
     TRISB = 0b00011110 ;       // 4 lower  bits are set as input
     OPTION_REG = 0x00 ;        //Enable pull-up resistor in PORTB and select HS Oscillator Source clock
/*
     bit 7 RBPU: PORTB Pull-up Enable bit
         1 = PORTB pull-ups are disabled
         0 = PORTB pull-ups are enabled by individual port latch values
     bit 6 INTEDG: Interrupt Edge Select bit
         1 = Interrupt on rising edge of RB0/INT pin
         0 = Interrupt on falling edge of RB0/INT pin
     bit 5 T0CS: TMR0 Clock Source Select bit
         1 = Transition on RA4/T0CKI pin
         0 = Internal instruction cycle clock (CLKO)
     bit 4 T0SE: TMR0 Source Edge Select bit
         1 = Increment on high-to-low transition on RA4/T0CKI pin
         0 = Increment on low-to-high transition on RA4/T0CKI pin
     bit 3 PSA: Prescaler Assignment bit
         1 = Prescaler is assigned to the WDT
         0 = Prescaler is assigned to the Timer0 module
     bit 2-0 PS2:PS0: Prescaler Rate Select bits
     Bit Value     TMR0 Rate     WDT Rate
     PS2-PS0
     000           1 : 2         1 : 1
     001           1 : 4         1 : 2
     010           1 : 8         1 : 4
     011           1 : 16        1 : 8
     100           1 : 32        1 : 16
     101           1 : 64        1 : 32
     110           1 : 128       1 : 64
     111           1 : 256       1 : 128
*/
     INTCON = 0b10001000;        // Enable RB4 interrupt on change,
     
     /*
     INTCON: Interrupt control Register
     GIE  PEIE  TMR0IE  INTE  RBIE  TMR0IF  INTF  RBIF
     bit7                                         bit0
     bit 7 GIE: Global Interrupt Enable bit
         1 = Enables all unmasked interrupts
         0 = Disables all interrupts
     bit 6 PEIE: Peripheral Interrupt Enable bit
         1 = Enables all unmasked peripheral interrupts
         0 = Disables all peripheral interrupts
     bit 5 TMR0IE: TMR0 Overflow Interrupt Enable bit
         1 = Enables the TMR0 interrupt
         0 = Disables the TMR0 interrupt
     bit 4 INTE: RB0/INT External Interrupt Enable bit
         1 = Enables the RB0/INT external interrupt
         0 = Disables the RB0/INT external interrupt
     bit 3 RBIE: RB Port Change Interrupt Enable bit
         1 = Enables the RB port change interrupt
         0 = Disables the RB port change interrupt
     bit 2 TMR0IF: TMR0 Overflow Interrupt Flag bit
         1 = TMR0 register has overflowed (must be cleared in software)
         0 = TMR0 register did not overflow
     bit 1 INTF: RB0/INT External Interrupt Flag bit
         1 = The RB0/INT external interrupt occurred (must be cleared in software)
         0 = The RB0/INT external interrupt did not occur
     bit 0 RBIF: RB Port Change Interrupt Flag bit
         1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to set
         the bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared
         (must be cleared in software).
         0 = None of the RB7:RB4 pins have changed state
     */

     Flag_RB4_PRESS  = 0;
     cnt = 0;
     SelectSegment_Timer = 1;
     
     TMR0 =0x00 ;              //Set default value for TMR0
     
     PS0_bit = 0;            //Set Source clock 1:8, interrupt each 16ms
     PS1_bit = 1;
     PS2_bit = 0;
     
     TMR0IE_bit = 0;           //enable timer0 interrup

     DS1307_Init();            // Inittation I2C protocol
     State = FSM_DISPLAY;      // Default State Machine
     
     if((p1.sec ==0x00) &&(p1.min ==0x00) && (p1.hour ==0x00)&& (p1.week_day ==0x00)&&
        (p1.day ==0x01) &&(p1.month ==0x01) && (p1.year ==0x01)){
        // Check data in for  fist running
         DS1307_DATA = 0;      // No data in DS1307
     }
     else{
         DS1307_DATA = 1;     // Yes data in DS1307
     }
     
     while (1) {                // Main loop

         switch (state){

             case(FSM_DISPLAY):
             DS1307_GetDateTime(&p1);
             if((!DS1307_DATA) ||(Flag_RB4_PRESS))
                // Not Data in DS1307 or RB0 is pressed.
             {
                 State = FSM_CONFIG;
             }
             else{
                 SegmentSixOrTwo = 1;
                 TMR0IE_bit = 1;
                 TMR0 = 0x00;
                 SevenSegmnet_Six_Display(p1.sec, p1.min, p1.hour);
                 TMR0IE_bit = 0;
                 //TMR0 = 0x80;
             }
             break;

             case(FSM_CONFIG):

                 SegmentSixOrTwo = 0;
                 TMR0IE_bit = 1;
                 TMR0 = 0x00;

                 while(1){

                     Get_Char_Button_Segment(60,4);
                     if(Button(&PORTB , 3, 1, PRESS)==255){              // SET_key is press
                         while(Button(&PORTB , 3, 1, PRESS)==255){;}     // Wait until SET_key is released
                         p1.sec = cnt;
                         cnt = 0;
                         break;
                     }
                 }

                 while(1){

                     Get_Char_Button_Segment(60,2);
                     if(Button(&PORTB , 3, 1, PRESS)==255){              // SET_key is press
                         while(Button(&PORTB , 3, 1, PRESS)==255){;}     // Wait until SET_key is released
                         p1.min = cnt;
                         cnt = 0;
                         break;
                     }
                 }

                 while(1){

                     Get_Char_Button_Segment(24,0);
                     if(Button(&PORTB , 3, 1, PRESS)==255){              // SET_key is press
                         while(Button(&PORTB , 3, 1, PRESS)==255){;}     // Wait until SET_key is released
                         p1.hour = cnt;
                         cnt = 0;
                         break;
                     }
                 }

                 DS1307_SetDateTime(&p1);
                 State = FSM_DISPLAY ;
                 Flag_RB4_PRESS = 0;     // Clear Flag
             break;
         }
     }
 }

/****************************************************************************
                           Define  Subfunction
*****************************************************************************/
 void Get_Char_Button_Segment( unsigned short Time_Threshold, unsigned short NumberSegment ){

     SevenSegmnet_Display(cnt,NumberSegment);
     if (Button(&PORTB , 2, 1, PRESS)){           // DOWN_Key is press
     
         while(Button(&PORTB , 2, 1 , PRESS)){
             ;
         }
         if (cnt == 0){
            cnt = Time_Threshold-1;
         }
         else{
             cnt--;
         }
         SevenSegmnet_Display(cnt,NumberSegment);
     }
     if(Button(&PORTB , 1, 1, PRESS)){              // UP_key is press
     
         while(Button(&PORTB , 1, 1, PRESS)){
             ;
         }     // Wait until UP_key is released
         cnt++;
         if( cnt == Time_Threshold) {
             cnt = 0;
         }

         SevenSegmnet_Display(cnt,NumberSegment);
     }
 }

/*void LCD_Make_TimeFormat(){
     Lcd_Out(1,12,"20");       // start from year 2000
 }*/
 void SevenSegmnet_Display( unsigned short n, unsigned short NumberSegment /*unsigned short SelectSegmentTimer*/){

     unsigned short i = 0;
     if(SelectSegment_TwoDigit){
         i = SevenSegment_DATA[n/10];
         PORTA = SevenSegment_DRIVE[NumberSegment];
         PORTD = i;
         //Delay_us(1300);
     }
     //delay();
     else 
     {
         i = SevenSegment_DATA[n% 10];
         PORTA = SevenSegment_DRIVE[NumberSegment+1];
         PORTD = i;
         //Delay_us(1300);
         //SelectSegment_TwoDigit = 0;
     }
     //delay();
 }
void SevenSegmnet_Six_Display(unsigned short sec, unsigned short min, unsigned short hour){

    unsigned short  i = 0;

    switch(SelectSegment_Timer){
        case 0:
         i= SevenSegment_DATA[sec/10];
            PORTA = SevenSegment_DRIVE[4];
            PORTD = i;
            break;
        case 1:
            i = SevenSegment_DATA[sec% 10];
            PORTA = SevenSegment_DRIVE[5];
            PORTD = i;
            break;
        case 2:
            i=SevenSegment_DATA[min%10];
            PORTA = SevenSegment_DRIVE[3];
            PORTD = i;
            break;
        case 3:
            i=SevenSegment_DATA[min/10];
            PORTA = SevenSegment_DRIVE[2];
            PORTD = i;
            break;
        case 4:
            i = SevenSegment_DATA[hour % 10];
            PORTA = SevenSegment_DRIVE[1];
            PORTD = i;
            break;
        case 5:
            i= SevenSegment_DATA[hour /10];
            PORTA = SevenSegment_DRIVE[0];
            PORTD = i;
            break;

        
    }
}
 
 #elif( TEST_MODULE == 8)
 #elif( TEST_MODULE == 9)
 #elif( TEST_MODULE == 10)
 #endif
 
/////////////////// END OF MAIN FUNCTION////////////////////////////////////////